package com.uzai.console.service.locallive.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.locallive.tlbtoken.*;
import com.uzai.console.entity.Merchant;
import com.uzai.console.entity.TlbToken;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.mapper.TlbTokenMapper;
import com.uzai.console.para.CheckTlbAppkeyAndAppidRemoteApiPara;
import com.uzai.console.service.locallive.TlbTokenService;
import com.uzai.console.service.remoteapi.TlbRemoteApiService;
import com.uzai.console.vo.locallive.tlbtoken.TenMillionSubsidiesVo;
import com.uzai.console.vo.locallive.tlbtoken.TlbTokenInfoVo;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 推老板联盟
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class TlbTokenServiceImpl implements TlbTokenService {

    Logger logger = LoggerFactory.getLogger(TlbTokenServiceImpl.class);

    @Autowired
    private TlbTokenMapper tlbTokenMapper;
    @Autowired
    private TlbRemoteApiService tlbRemoteApiService;
    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 查询推老板联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tlbTokenQuery
     * @return null
     */
    public Page<TlbTokenInfoVo> findTlbTokenList(TlbTokenQuery tlbTokenQuery){
        //新建返回到页面的LIST对象
        List<TlbTokenInfoVo> tlbTokenInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<TlbToken> page = new Page<>();
        tlbTokenQuery.convert(page);
        ArrayList<TlbToken> tlbOrderList =  tlbTokenMapper.findByList(page, tlbTokenQuery);
        if(tlbOrderList != null && tlbOrderList.size() > 0){
            for (TlbToken tlbToken : tlbOrderList){
                TlbTokenInfoVo tlbTokenInfoVo = new TlbTokenInfoVo();
                BeanUtils.copyProperties(tlbToken, tlbTokenInfoVo);
                tlbTokenInfoVoList.add(tlbTokenInfoVo);
            }
        }

        //返回到页面分页对象
        Page<TlbTokenInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(tlbTokenInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询推老板联盟详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tlbTokenIdDto
     * @return null
     */
    public TlbTokenInfoVo findTlbTokenInfo(TlbTokenIdDto tlbTokenIdDto){

        if(tlbTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        TlbToken tlbToken = tlbTokenMapper.selectById(tlbTokenIdDto.getId(), tlbTokenIdDto.getMerId());
        if(tlbToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该推老板联盟账号不存在");
        }

        //返回页面对象
        TlbTokenInfoVo tlbTokenInfoVo = new TlbTokenInfoVo();
        //将查询到的对象复制给返回页面对象
        BeanUtils.copyProperties(tlbToken, tlbTokenInfoVo);

        return tlbTokenInfoVo;
    }

    /**
     * 添加推老板联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tlbTokenInfoDto
     * @return null
     */
    public TlbToken addTlbToken(TlbTokenInfoDto tlbTokenInfoDto){
        Integer now = DateUtil.getNowTime();

        if(StringUtils.isBlank(tlbTokenInfoDto.getAppId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入appId");
        }

        if(StringUtils.isBlank(tlbTokenInfoDto.getAppKey())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入appKey");
        }

        //验证appId和appkey正确性
        CheckTlbAppkeyAndAppidRemoteApiPara checkTlbAppkeyAndAppidRemoteApiPara = new CheckTlbAppkeyAndAppidRemoteApiPara();
        checkTlbAppkeyAndAppidRemoteApiPara.setAppid(tlbTokenInfoDto.getAppId());
        checkTlbAppkeyAndAppidRemoteApiPara.setAppkey(tlbTokenInfoDto.getAppKey());
        boolean checked = tlbRemoteApiService.checkTlbAppkeyAndAppid(checkTlbAppkeyAndAppidRemoteApiPara);
        if(!checked){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入正确的推老板appid和appkey");
        }

        TlbToken tlbToken_old = tlbTokenMapper.selectByAppId(tlbTokenInfoDto.getAppId());
        if(tlbToken_old != null){
            if(tlbToken_old.getMerId().longValue() != tlbTokenInfoDto.getMerId().longValue()){
                String mobile = "";
                Merchant merchant = merchantMapper.selectById(tlbToken_old.getMerId());
                if(merchant != null){
                    //脱敏
                    mobile = DesensitizeUtil.around(Tools.getStr(merchant.getMobile()),3,4);
                }
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "appId已经给其他运营商使用(运营商账号:"+mobile+")");
            }
            //token共用
            List<String> typeList = null;
            try {
                typeList = JSONObject.parseArray(tlbToken_old.getType(), String.class);
            }catch (Exception e ){}
            if(typeList == null ){
                typeList = new ArrayList<>();
            }

            if(typeList.contains(tlbTokenInfoDto.getType())){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此appId已存在");
            }
            typeList.add(tlbTokenInfoDto.getType());
            tlbToken_old.setType(Tools.getStrEmpty(JSONObject.toJSONString(typeList)));
            tlbToken_old.setRemark(tlbTokenInfoDto.getRemark());
            tlbToken_old.setUpdateTime(now);
            tlbTokenMapper.updateById(tlbToken_old);

            return tlbToken_old;

        }else{//数据库当中不存在，为空，则新插入
            TlbToken tlbToken = new TlbToken();
            BeanUtils.copyProperties(tlbTokenInfoDto, tlbToken);
            tlbToken.setId(IdWorker.getId());
            tlbToken.setMerId(tlbTokenInfoDto.getMerId());
            tlbToken.setAppId(tlbTokenInfoDto.getAppId());
            tlbToken.setAppKey(tlbTokenInfoDto.getAppKey());
            List<String> typeList = new ArrayList<>();
            typeList.add(tlbTokenInfoDto.getType());
            tlbToken.setType(Tools.getStrEmpty(JSONObject.toJSONString(typeList)));
            tlbToken.setRemark(tlbTokenInfoDto.getRemark());
            tlbToken.setCreateTime(now);
            tlbToken.setUpdateTime(now);
            tlbTokenMapper.insertSelective(tlbToken);

            return tlbToken;
        }
    }

    /**
     * 修改推老板联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tlbTokenInfoDto
     * @return null
     */
    public void updateTlbToken(TlbTokenInfoDto tlbTokenInfoDto){

        if(tlbTokenInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        if(StringUtils.isBlank(tlbTokenInfoDto.getAppKey())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入appKey");
        }

        TlbToken tlbToken = tlbTokenMapper.selectById(tlbTokenInfoDto.getId(), tlbTokenInfoDto.getMerId());

        if(tlbToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "联盟不存在");
        }

        //验证appId和appkey正确性
        CheckTlbAppkeyAndAppidRemoteApiPara checkTlbAppkeyAndAppidRemoteApiPara = new CheckTlbAppkeyAndAppidRemoteApiPara();
        checkTlbAppkeyAndAppidRemoteApiPara.setAppid(tlbToken.getAppId());
        checkTlbAppkeyAndAppidRemoteApiPara.setAppkey(tlbTokenInfoDto.getAppKey());
        boolean checked = tlbRemoteApiService.checkTlbAppkeyAndAppid(checkTlbAppkeyAndAppidRemoteApiPara);
        if(!checked){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入正确的推老板appid和appkey");
        }

        Integer now = DateUtil.getNowTime();
        tlbToken.setAppKey(tlbTokenInfoDto.getAppKey());
        tlbToken.setRemark(tlbTokenInfoDto.getRemark());
        tlbToken.setUpdateTime(now);
        tlbTokenMapper.updateById(tlbToken);
    }

    /**
     * 删除联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tlbTokenIdDto
     * @return null
     */
    public void deleteTlbToken(TlbTokenIdDto tlbTokenIdDto){
        if(tlbTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        TlbToken tlbToken = tlbTokenMapper.selectById(tlbTokenIdDto.getId(), tlbTokenIdDto.getMerId());
        if(tlbToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "推老板联盟不存在");
        }

        if(StringUtils.isNotBlank(tlbToken.getType())){
            //如果删除的类型不为空，则只修改类型，如果为空，则删除推老板联盟
            if(StringUtils.isNotBlank(tlbTokenIdDto.getType())){
                List<String> typeList = JSONObject.parseArray(tlbToken.getType(), String.class);
                if(typeList != null && typeList.size() > 1){ //大于2个才执行，只有一个类型，则直接删除
                    typeList.remove(tlbTokenIdDto.getType());
                    if(typeList.size() > 0 ){
                        tlbToken.setType(Tools.getStrEmpty(JSONObject.toJSONString(typeList)));
                        tlbTokenMapper.updateByIdSelective(tlbToken);
                    }else{
                        tlbTokenMapper.deleteById(tlbTokenIdDto.getId(), tlbTokenIdDto.getMerId());
                    }
                }{
                    tlbTokenMapper.deleteById(tlbTokenIdDto.getId(), tlbTokenIdDto.getMerId());
                }
            }else{
                tlbTokenMapper.deleteById(tlbTokenIdDto.getId(), tlbTokenIdDto.getMerId());
            }
        }else{ //如果类型为空，直接删除
            tlbTokenMapper.deleteById(tlbTokenIdDto.getId(), tlbTokenIdDto.getMerId());
        }

    }

    /**
     * 查询所有推老板联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tlbTokenQuery
     * @return null
     */
    public List<TlbTokenInfoVo> findTlbTokenListSelect(TlbTokenQuery tlbTokenQuery){
        //新建返回到页面的LIST对象
        List<TlbTokenInfoVo> tlbTokenInfoVoList = new ArrayList<>();
        ArrayList<TlbToken> tlbOrderList =  tlbTokenMapper.findByList(tlbTokenQuery);
        if(tlbOrderList != null && tlbOrderList.size() > 0){
            for (TlbToken tlbToken : tlbOrderList){
                TlbTokenInfoVo tlbTokenInfoVo = new TlbTokenInfoVo();
                BeanUtils.copyProperties(tlbToken, tlbTokenInfoVo);
                tlbTokenInfoVoList.add(tlbTokenInfoVo);
            }
        }
        return tlbTokenInfoVoList;
    }

    @Override
    public List<TlbToken> listTlbToken(Long merId, List<Long> leagueAccountIds) {
        if (Objects.isNull(merId) || CollectionUtil.isEmpty(leagueAccountIds)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<TlbToken> condition = Wrappers.lambdaQuery(TlbToken.class);
        condition.eq(TlbToken::getMerId, merId).in(TlbToken::getId, leagueAccountIds);
        return tlbTokenMapper.selectList(condition);
    }

}
